package com.cnfangmao.masterdata.controller;

import javax.validation.constraints.NotNull;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cnfangmao.masterdata.common.response.ResCodeEnum;
import com.cnfangmao.masterdata.common.response.ResBody;
import com.cnfangmao.masterdata.common.util.MD5Utils;
import com.cnfangmao.masterdata.dto.AccountDto;
import com.cnfangmao.masterdata.dto.AccountSearchDto;
import com.cnfangmao.masterdata.dto.ChangePasswordDto;
import com.cnfangmao.masterdata.dto.GeneralSearchDto;
import com.cnfangmao.masterdata.model.Account;
import com.cnfangmao.masterdata.service.AccountService;
import com.cnfangmao.masterdata.vo.GeneralPageVo;

/**
 * <p>
 * 主数据中心用户 前端控制器
 * </p>
 *
 * @author chenxd
 * @since 2020-04-14
 */
@RequestMapping("/account")
@Api(tags = "0-2、配置-用户管理")
@RestController
public class AccountController {

	private static final Logger logger =LoggerFactory.getLogger(AccountController.class);

	@Autowired
	private AccountService accountService;

	/**
	 * 用户列表
	 */
	@RequestMapping(value = "/list.do", method = RequestMethod.POST)
	@ApiOperation(value = "用户列表", notes = "")
	@ApiImplicitParam(name = "dto", value = "用户列表查询条件", required = true, paramType = "body", dataType = "GeneralSearchDto«AccountSearchDto»")
	public ResBody<GeneralPageVo<Account>>  listAccount(@RequestBody GeneralSearchDto<AccountSearchDto> dto) {
		 ResBody<GeneralPageVo<Account>> resBody = new  ResBody<GeneralPageVo<Account>>();;
		try {
			IPage<Account> data = accountService.queryListAccount(dto);
			GeneralPageVo<Account> result= new GeneralPageVo<Account>();
			result.setPageNo(data.getCurrent());
			result.setPageSize(data.getPages());
			result.setRecords(data.getRecords());
			result.setTotalCount(data.getTotal());
			resBody.code(ResCodeEnum.SUCCESS.getCode());
			resBody.data(result);
			resBody.message("查询成功");
		} catch (Exception e) {
			logger.error(String.format("run list error in AccountController：%s",e.getMessage()));
			resBody.code(ResCodeEnum.FAIL.getCode());
			resBody.message(e.getMessage());
		}
		return resBody;
	}

	/**
	 * 创建用户
	 */
	@RequestMapping(value = "/create.do", method = RequestMethod.POST)
	@ApiOperation(value = "创建用户", notes = "")
	@ApiImplicitParam(name = "dto", value = "创建用户信息", required = true, paramType = "body", dataType = "AccountDto")
	public ResBody<Boolean> createAccount(@Validated @RequestBody @NotNull AccountDto dto) {
		ResBody<Boolean> resBody = new ResBody<Boolean>();
		try {
			if (dto.getUserName().isEmpty()) {
				resBody.code(ResCodeEnum.PARAM_NULL.getCode());
				resBody.message("用户名为空");
				return resBody;
			}
			if (accountService.findByUserName(dto.getUserName()) != null) {
				resBody.code(ResCodeEnum.PARAM_NULL.getCode());
				resBody.message("用户名已经存在");
				return resBody;
			}
			accountService.saveAccount(dto, "");
			resBody.code(ResCodeEnum.SUCCESS.getCode());
			resBody.data(true);
			resBody.message("创建成功");
		} catch (Exception e) {
			logger.error(String.format("run create error in AccountController：%s",e.getMessage()));
			resBody.code(ResCodeEnum.FAIL.getCode());
			resBody.message(e.getMessage());
		}
		return resBody;
	}

	/**
	 * 更新用户信息
	 */
	@RequestMapping(value = "/update.do", method = RequestMethod.POST)
	@ApiOperation(value = "更新用户", notes = "")
	@ApiImplicitParam(name = "dto", value = "更新用户信息", required = true, paramType = "body", dataType = "AccountDto")
	public ResBody<Boolean> updateAccount(@Validated @RequestBody @NotNull AccountDto dto) {
		ResBody<Boolean> resBody = new ResBody<Boolean>();
		try {
			if (dto.getUserName().isEmpty()) {
				resBody.code(ResCodeEnum.PARAM_NULL.getCode());
				resBody.message("用户名为空");
				return resBody;
			}
			Account account = accountService.findByUserName(dto.getUserName());
			if (account != null && !account.getUserId().equals(dto.getUserId())) {
				resBody.code(ResCodeEnum.PARAM_NULL.getCode());
				resBody.message("用户名已经存在");
				return resBody;
			}
			accountService.update(dto, "");
			resBody.code(ResCodeEnum.SUCCESS.getCode());
			resBody.data(true);
			resBody.message("修改成功");
		} catch (Exception e) {
			logger.error(String.format("run update error in AccountController：%s",e.getMessage()));
			resBody.code(ResCodeEnum.FAIL.getCode());
			resBody.message(e.getMessage());
		}	
		return resBody;
	}

	@RequestMapping(value = "/delete.do", method = RequestMethod.POST)
	@ApiOperation(value = "删除用户", notes = "")
	@ApiImplicitParam(name = "userId", value = "用户userId",paramType = "body", required = true, dataType = "string")
	public ResBody<Boolean> deleteAccount(@Validated @RequestBody @NotNull String userId) {
		ResBody<Boolean> resBody = new ResBody<Boolean>();
		try {
			accountService.delete(userId);
			resBody.code(ResCodeEnum.SUCCESS.getCode());
			resBody.data(true);
			resBody.message("删除成功");
		} catch (Exception e) {
			logger.error(String.format("run delete error in AccountController：%s",e.getMessage()));
			resBody.code(ResCodeEnum.FAIL.getCode());
			resBody.message(e.getMessage());
		}
		return resBody;
	}
	
	/**
     * 获取用户详情
     */
    @RequestMapping(value="/getAccount.do", method = RequestMethod.POST)
    @ApiOperation(value="获取用户详情", notes = "")
    @ApiImplicitParam(name = "userId", value = "角色userId", required = true, paramType = "body",dataType = "string")
    public ResBody<Account> getAccount(@Validated @RequestBody @NotNull String userId){
    	ResBody<Account> resBody = new ResBody<Account>();
    	try {
        	Account account=accountService.getById(userId);
        	resBody.code(ResCodeEnum.SUCCESS.getCode());
			resBody.data(account);
		} catch (Exception e) {
			logger.error(String.format("run getAccount error in AccountController：%s",e.getMessage()));
			resBody.code(ResCodeEnum.FAIL.getCode());
			resBody.message(e.getMessage());
		}
    	return resBody;
    }
    
    /**
	 * 修改用户密码
	 */
	@RequestMapping(value = "/changePassword.do", method = RequestMethod.POST)
	@ApiOperation(value = "修改用户密码", notes = "")
	@ApiImplicitParam(name = "dto", value = "修改用户密码", required = true, paramType = "body", dataType = "ChangePasswordDto")
	public ResBody<Boolean> changePassword(@Validated @RequestBody @NotNull ChangePasswordDto dto) {
		ResBody<Boolean> resBody = new ResBody<Boolean>();
        try {
    		Account account = accountService.getById(dto.getUserId());
    		if (account != null && !account.getPassword().equals(MD5Utils.getMD516(dto.getOriginalPassword()))) {
    			resBody.code(ResCodeEnum.PARAM_NULL.getCode());
    			resBody.message("用户名原密码错误");
    			return resBody;
    		}
    		accountService.changePassword(dto);
    		resBody.code(ResCodeEnum.SUCCESS.getCode());
    		resBody.data(true);
    		resBody.message("修改成功");
		} catch (Exception e) {
			logger.error(String.format("run changePassword error in AccountController：%s",e.getMessage()));
			resBody.code(ResCodeEnum.FAIL.getCode());
			resBody.message(e.getMessage());
		}
		return resBody;
	}
}
